package com.example.demo.practice.dashboardview;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.demo.practice.R;
import com.example.demo.practice.enterprise.Auditinfo;
import com.example.demo.practice.httpserver.HttpServer;
import com.example.demo.practice.monitor.EnterpriseEvaluation;
import com.example.demo.practice.ui.TitleView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PListView extends Activity {
    private HttpServer http = new HttpServer();
    private String HTTP = http.getHttp();

    private RelativeLayout regionselect;
    private TitleView select;
    private ImageView selection;
    private TitleView regionname;
    private AutoCompleteTextView search;
    private ImageView searchStart;
    private ListView list1;
    private ListView list2;
    private ListView listmain;
    private ArrayList<String> region1 = new ArrayList<>();
    private ArrayList<String> region2 = new ArrayList<>();
    private JSONArray jSONArray;
    private List<Auditinfo> mlistInfo = new ArrayList<>();
    private List<Auditinfo> mlistInfomain = new ArrayList<>();
    private ArrayList<String> category = new ArrayList<>();
    private ArrayList<ArrayList<String>> subcategory = new ArrayList<>();
    private ArrayList<ArrayList<String>> allcpm = new ArrayList<>();
    private ArrayList<String> allcpnName = new ArrayList<>();

    private String next;

    public class ListViewAdapter extends BaseAdapter {
        View[] itemViews;

        public ListViewAdapter(List<Auditinfo> mlistInfo) {
            // TODO Auto-generated constructor stub
            itemViews = new View[mlistInfo.size()];
            for(int i=0;i<mlistInfo.size();i++){
                Auditinfo getInfo=mlistInfo.get(i);    //获取第i个对象
                //调用makeItemView，实例化一个Item
                itemViews[i]=makeItemView(
                        getInfo.getText1()
                );
            }
        }

        public int getCount() {
            return itemViews.length;
        }

        public View getItem(int position) {
            return itemViews[position];
        }

        public long getItemId(int position) {
            return position;
        }

        //绘制Item的函数
        private View makeItemView(String strText1) {
            LayoutInflater inflater = (LayoutInflater) PListView.this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            // 使用View的对象itemView与R.layout.item关联
            View itemView = inflater.inflate(R.layout.regionselect_item, null);

            // 通过findViewById()方法实例R.layout.item内各组件
            TextView text1 = itemView.findViewById(R.id.text);
            text1.setText(strText1);    //填入相应的值

            return itemView;
        }


        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null)
                return itemViews[position];
            return convertView;
        }
    }

    public void setInfo(ArrayList<String> ArrayList){
        mlistInfo.clear();
        int i=0;
        while(i<ArrayList.size()){
            Auditinfo information = new Auditinfo();
            information.setId(Integer.toString(i));
            information.setText1(ArrayList.get(i));

            mlistInfo.add(information); //将新的info对象加入到信息列表中
            i++;
        }
    }

    public class ListViewAdapterMain extends BaseAdapter {
        View[] itemViews;

        public ListViewAdapterMain(List<Auditinfo> mlistInfo) {
            // TODO Auto-generated constructor stub
            itemViews = new View[mlistInfo.size()];
            for(int i=0;i<mlistInfo.size();i++){
                Auditinfo getmainInfo=mlistInfo.get(i);    //获取第i个对象
                //调用makeItemView，实例化一个Item
                itemViews[i]=makemainItemView(
                        getmainInfo.getText1(), getmainInfo.getText2()
                );
            }
        }

        public int getCount() {
            return itemViews.length;
        }

        public View getItem(int position) {
            return itemViews[position];
        }

        public long getItemId(int position) {
            return position;
        }


        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null)
                return itemViews[position];
            return convertView;
        }

        //绘制Item的函数
        private View makemainItemView(String strText1, String strText2) {
            LayoutInflater inflater = (LayoutInflater) PListView.this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            // 使用View的对象itemView与R.layout.item关联
            View itemView = inflater.inflate(R.layout.alllist_item, null);

            // 通过findViewById()方法实例R.layout.item内各组件
            TextView text1 = itemView.findViewById(R.id.text1);
            text1.setText(strText1);    //填入相应的值
            TextView text2 = itemView.findViewById(R.id.text2);
            text2.setText(strText2);

            return itemView;
        }
    }

    public void setmainInfo(){
        mlistInfomain.clear();
        int i = 0;
        while(i<allcpm.size()){
                Auditinfo information = new Auditinfo();
                information.setId(Integer.toString(i));
                information.setText1(allcpm.get(i).get(0));
                information.setText2(allcpm.get(i).get(1));
                mlistInfomain.add(information); //将新的info对象加入到信息列表中
            i++;
        }
    }
    public void selectmainInfo(int i){
        mlistInfomain.clear();
        int j = 0;
        while(j<subcategory.get(i).size()){
            Auditinfo information = new Auditinfo();
            information.setId(Integer.toString(i));
            information.setText1(subcategory.get(i).get(j));
            information.setText2(subcategory.get(i).get(j+1));
            mlistInfomain.add(information); //将新的info对象加入到信息列表中
            j = j + 2;
        }
    }
    public void setSearchStart(String name){
        mlistInfomain.clear();
        int i = 0;
        while(i<allcpm.size()){
            if(allcpm.get(i).get(0).equals(name)){
                Auditinfo information = new Auditinfo();
                information.setId(Integer.toString(i));
                information.setText1(allcpm.get(i).get(0));
                information.setText2(allcpm.get(i).get(1));
                mlistInfomain.add(information); //将新的info对象加入到信息列表中
            }
            i++;
        }
    }

    public void Ave(){
        region1.add("全部");
        for (int i = 0;i < category.size();i++){
            if(i % 2 == 0){
                region2.add(category.get(i));
            }else {
                region1.add(category.get(i));
            }
        }
    }

    public void AddRegion(){
        setInfo(region1);
        list1.setAdapter(new PListView.ListViewAdapter(mlistInfo));
        setInfo(region2);
        list2.setAdapter(new PListView.ListViewAdapter(mlistInfo));
        //处理Item的点击事件
        list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                regionselect.setVisibility(View.GONE);
                if(position == 0){
                    regionname.setText("全部");
                    setmainInfo();
                }else{
                    position = position * 2 - 1;
                    Auditinfo getObject = mlistInfo.get(position);   //通过position获取所点击的对象
                    String text = getObject.getText1(); //获取信息
                    regionname.setText(text);
                    selectmainInfo(position);
                }
                listmain.setAdapter(new PListView.ListViewAdapterMain(mlistInfomain));
            }
        });
        list2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                regionselect.setVisibility(View.GONE);
                position = position * 2;
                Auditinfo getObject = mlistInfo.get(position);   //通过position获取所点击的对象
                String text = getObject.getText1(); //获取信息
                regionname.setText(text);
                selectmainInfo(position);
                listmain.setAdapter(new PListView.ListViewAdapterMain(mlistInfomain));
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            for (int i = 0; i < jSONArray.length(); i++) {
                JSONObject json = null;
                ArrayList<String> sub = new ArrayList<>();
                try {
                    json = (JSONObject) jSONArray.get(i);
                    String name = json.getString("name");
                    String admregion = json.getString("admregion");

                    sub.add(name);
                    sub.add(admregion);
                    allcpm.add(sub);
                    allcpnName.add(name);

                    int n = 0;
                    for(int j = 0; j < category.size();j++){
                        String Name = category.get(j);
                        if (Name.equals(admregion))
                            n++;
                    }
                    if(n == 0) {
                        sub.add(name);
                        sub.add(admregion);
                        category.add(admregion);
                        subcategory.add(sub);
                    }
                    else {
                        for (int k = 0; k < category.size(); k++) {
                            if (category.get(k).equals(admregion)) {
                                subcategory.get(k).add(name);
                                subcategory.get(k).add(admregion);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            jSONArray=null;

            setmainInfo();
            listmain.setAdapter(new PListView.ListViewAdapterMain(mlistInfomain));
            listmain.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Auditinfo getObject = mlistInfomain.get(position);   //通过position获取所点击的对象
                    String text = getObject.getText1();
                    try {
                        Intent intent = new Intent(PListView.this, Class.forName(next));
                        intent.putExtra("name",text);
                        startActivity(intent);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });
            Ave();
            AddRegion();
            setInfo(category);


            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plist_view);
        regionselect = findViewById(R.id.regionselect);
        list1 = findViewById(R.id.list1);
        list2 = findViewById(R.id.list2);
        listmain = findViewById(R.id.listmain);
        select = findViewById(R.id.select);
        selection = findViewById(R.id.selections);
        regionname = findViewById(R.id.regionname);
        searchStart = findViewById(R.id.searchStart);
        search = findViewById(R.id.search);

        Intent intent=getIntent();
        next=intent.getStringExtra("next");

        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(regionselect.getVisibility() == View.GONE){
                    regionselect.setVisibility(View.VISIBLE);
                }else{
                    regionselect.setVisibility(View.GONE);
                }
            }
        });
        selection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(regionselect.getVisibility() == View.GONE){
                    regionselect.setVisibility(View.VISIBLE);
                }else{
                    regionselect.setVisibility(View.GONE);
                }
            }
        });
        searchStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String SearchName = search.getText().toString().trim();
                setSearchStart(SearchName);
                listmain.setAdapter(new PListView.ListViewAdapterMain(mlistInfomain));
            }
        });
        getVideoData();
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,allcpnName);
        search.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.expandable_list_view, menu);
        return true;
    }

    /**
     * 获取视频监控设备信息
     */
    private void getVideoData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象
                    Request request = new Request.Builder()
                            .url(HTTP + "Enterprise")//请求接口。如果需要传参拼接到接口后面。
                            .build();//创建Request 对象

                    Response response = client.newCall(request).execute();//得到Response 对象
                    if (response.isSuccessful()) {
                        Log.e("kwwl", "response.code()==" + response.code());
                        Log.e("kwwl", "response.message()==" + response.message());
                        //response.body().string()只可以调用一次
                        //此时的代码执行在子线程，修改UI的操作请使用handler跳转到UI线程。
                        jSONArray = new JSONArray(response.body().string());
                        handler.sendEmptyMessage(0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
